package com.banfan.almond.web.security;

import com.banfan.almond.web.global.JwtConf;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;


@Slf4j
public class JwtUtil {

    private final static String Base_64_SECRET = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=";

    private final static int EXPIRES_SECOND = 1000 * 60 * 60; //2小时

    public static Claims parseJWT(String jsonWebToken) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(Base_64_SECRET))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (ExpiredJwtException ex) {
            log.info("token过期");
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    public static String createJWT(String username, long minute) {
        //加密算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        //现在时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Base_64_SECRET);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .claim(JwtConf.USERNAME, username)
                .claim(JwtConf.CREATE_TIME, now)
                .signWith(SignatureAlgorithm.HS256, signingKey);


        //添加Token过期时间
        if (EXPIRES_SECOND >= 0) {
            long expMillis = nowMillis + EXPIRES_SECOND * minute;
            Date expired = new Date(expMillis);
            builder.setExpiration(expired).setNotBefore(now);
        }

        //生成JWT
        String compact = builder.compact();

        log.info("生成 jwt : {}", compact);
        return compact;

    }


    public static String getUsername(String jsonWebToken) {
        try {
            Claims claims = parseJWT(jsonWebToken);
            String o = (String) claims.get(JwtConf.USERNAME);
            return o;
        } catch (Exception e) {
            return null;
        }

    }


}
